package com.dkd.sbtz.service;

// src/main/java/com/dkd/sbtz/service/storage/StorageService.java

import com.dkd.common.config.RuoYiConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.*;

@Component
public class StorageService {

    // RuoYi 本地上传根目录（按你的项目配置改名）
    // ① 若有 RuoYiConfig.getProfile()，可不用这个 @Value；
    // ② 若无，则在 application.yml 配置：file.profile: /data/profile
//    @Value("${file.profile:/home/ruoyi/uploadPath}")
//    private String profileDir;
    String profileDir = RuoYiConfig.getProfile();

    private static final String PROFILE_PREFIX = "/profile";

    /** 根据 fileUrl 打开 InputStream，支持本地/HTTP */
    public InputStream open(String fileUrl) throws IOException {
        if (fileUrl == null || fileUrl.isEmpty()) {
            throw new FileNotFoundException("fileUrl is empty");
        }
        String u = fileUrl.trim();

        // 远程 http(s)
        if (u.startsWith("http://") || u.startsWith("https://")) {
            URLConnection conn = new URL(u).openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(15000);
            return conn.getInputStream();
        }

        if (u.startsWith("minio://")) {
            return openMinio(u);
        }

        // 本地路径解析（支持 /profile/** 或相对路径）
        String local = u;
        if (u.startsWith(PROFILE_PREFIX + "/")) {
            // /profile/upload/xxx => /data/profile/upload/xxx
            local = profileDir + u.substring(PROFILE_PREFIX.length());
        } else if (!u.startsWith(File.separator)) {
            // 相对路径 => 挂到 profile 根下
            local = Paths.get(profileDir, u).toString();
        }

        Path path = Paths.get(local).normalize();

        // 目录穿越保护：必须在 profile 根下
        Path base = Paths.get(profileDir).normalize();
        if (path.startsWith(base)) {
            return Files.newInputStream(path, StandardOpenOption.READ);
        }

        // 如果本地不是以 profile 开头（你确实给了绝对路径），也允许
        if (Files.exists(path)) {
            return Files.newInputStream(path, StandardOpenOption.READ);
        }

        throw new FileNotFoundException("File not found: " + u + " -> " + path);
    }


    private InputStream openMinio(String uri) throws IOException {
        try {
            java.net.URI u = java.net.URI.create(uri); // minio://bucket/object
            String bucket = u.getHost();
            String object = u.getPath().replaceFirst("^/", "");
            // return minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(object).build());
            throw new UnsupportedOperationException("Inject MinioClient and enable the code.");
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
}
